package jobs;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import controllers.Attachments;

import models.Attachment;
import play.Logger;
import play.Play;
import play.jobs.Every;
import play.jobs.Job;

/**
 * 清理废弃的附件
 * @author justin
 *
 */
@Every("1h")
public class CleanupAttachments extends Job{

	/**
	 * 删除2小时前，used标记未标记为true的附件
	 */
	@Override
	public void doJob() throws Exception {
		Logger.info("执行附件清理");
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR_OF_DAY, -2);
		
		List<Attachment> as = Attachment.find("createAt < ? and used != true", c.getTime()).fetch();
		for(Attachment a : as){
			if(null != a.filePath){
				File file = Play.getFile(Attachments.uploadPath + a.filePath);
				file.delete();
			}
			a.delete();
		}
	}
}
